<template>
  <div class="point-detail-container">
    <el-card class="point-info-card">
      <div class="point-header">
        <h3 class="point-title">{{ pointDetail.pointName || '未命名点位' }}</h3>
        <el-tag :type="pointDetail.status === 1 ? 'success' : 'danger'">
          {{ pointDetail.status === 1 ? '启用' : '禁用' }}
        </el-tag>
      </div>

      <div class="point-basic-info">
        <div class="info-row">
          <span class="info-label">点位ID：</span>
          <span class="info-value">{{ pointDetail.pointId || '-' }}</span>
          <span class="info-label ml-4">所属社区：</span>
          <span class="info-value">{{ pointDetail.communityName || '-' }}</span>
        </div>

        <div class="info-row">
          <span class="info-label">点位分类：</span>
          <span class="info-value">{{ pointDetail.categoryName || '-' }}</span>
          <span class="info-label ml-4">位置编号：</span>
          <span class="info-value">{{ pointDetail.locationNo || '-' }}</span>
        </div>

        <div class="info-row">
          <span class="info-label">所属楼宇：</span>
          <span class="info-value">{{ pointDetail.buildingName || '-' }}</span>
          <span class="info-label ml-4">单元：</span>
          <span class="info-value">{{ pointDetail.unit || '-' }}</span>
        </div>

        <div class="info-row">
          <span class="info-label">经纬度：</span>
          <span class="info-value">{{ pointDetail.longitude || '-' }}, {{ pointDetail.latitude || '-' }}</span>
          <span class="info-label ml-4">拍照要求：</span>
          <span class="info-value">
            <el-tag type="info">{{ pointDetail.photoRequired === 1 ? '需要拍照' : '无需拍照' }}</el-tag>
          </span>
        </div>

        <div class="info-row">
          <span class="info-label">最近巡检时间：</span>
          <span class="info-value">{{ formatDateTime(pointDetail.lastCheckInTime) || '从未巡检' }}</span>
          <span class="info-label ml-4">巡检次数：</span>
          <span class="info-value">{{ pointDetail.checkInCount || 0 }} 次</span>
        </div>

        <div class="info-row full-width">
          <span class="info-label">异常记录：</span>
          <span class="info-value">
            <el-tag type="danger" v-if="pointDetail.exceptionCount > 0">
              {{ pointDetail.exceptionCount }} 条异常
            </el-tag>
            <span v-else>无异常记录</span>
          </span>
        </div>
      </div>

      <!-- 点位位置地图 -->
      <div class="point-map-section">
        <h4 class="section-title">点位位置</h4>
        <div class="map-container" v-if="pointDetail.longitude && pointDetail.latitude">
          <el-image
              :src="getMapImage()"
              :preview-src-list="[getMapImage()]"
              fit="contain"
              class="map-image"
          >
            <template #placeholder>
              <div class="image-placeholder">加载地图中...</div>
            </template>
            <template #error>
              <div class="image-error">
                <el-icon><PictureFilled /></el-icon>
                <span>地图加载失败</span>
              </div>
            </template>
          </el-image>
        </div>
        <div class="no-map-data" v-else>
          <p>暂无位置信息</p>
        </div>
      </div>

      <!-- 最近巡检记录 -->
      <div class="recent-checkins">
        <h4 class="section-title">最近3次巡检记录</h4>
        <el-table
            :data="recentCheckins"
            border
            style="width: 100%;"
            v-if="recentCheckins.length > 0"
        >
          <el-table-column prop="checkInTime" label="巡检时间" width="180" />
          <el-table-column prop="checkInUser" label="巡检人员" width="120" />
          <el-table-column label="巡检结果" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.result === '正常' ? 'success' : 'danger'">
                {{ scope.row.result }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
        </el-table>
        <div class="no-checkins" v-else>
          <p>暂无巡检记录</p>
        </div>
      </div>
    </el-card>

    <div class="point-actions">
      <el-button
          type="default"
          @click="$emit('close')"
      >
        关闭
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { ElMessage, ElNotification } from 'element-plus';
import { PictureFilled, Location, Clock, Check, WarningFilled } from '@element-plus/icons-vue';

// 导入API
import { getPointDetail, getPointCheckins } from '../api/patrolPoint';

// 接收父组件传递的点位ID
const props = defineProps({
  pointId: {
    type: String,
    required: true
  }
});

// 响应式数据
const pointDetail = ref({});
const recentCheckins = ref([]);
const loading = ref(false);

// 加载点位详情
const loadPointDetail = async () => {
  try {
    loading.value = true;
    let {data:data} = await getPointDetail(props.pointId);

    if (data.code === 0) {
      pointDetail.value = data.data || {};
    } else {
      ElMessage.error(data.message || '获取点位详情失败');
    }
  } catch (error) {
    console.error('获取点位详情失败:', error);
    ElMessage.error('获取点位详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 加载最近巡检记录
const loadRecentCheckins = async () => {
  try {
    let {data:data} = await getPointCheckins({
      pointId: props.pointId,
      pageSize: 3 // 只获取最近3条
    });

    if (data.code === 0) {
      recentCheckins.value = data.data.records || [];
    } else {
      console.warn('获取巡检记录失败:', data.message);
    }
  } catch (error) {
    console.error('获取巡检记录失败:', error);
  }
};

// 生成地图图片URL（模拟，实际项目需对接地图API）
const getMapImage = () => {
  // 实际项目中可替换为百度/高德地图静态图API
  const { longitude, latitude } = pointDetail.value;
  return `https://picsum.photos/seed/${longitude}${latitude}/800/400`;
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-';
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 监听点位ID变化，重新加载数据
watch(() => props.pointId, (newVal) => {
  if (newVal) {
    loadPointDetail();
    loadRecentCheckins();
  }
});

// 组件挂载时加载数据
onMounted(() => {
  if (props.pointId) {
    loadPointDetail();
    loadRecentCheckins();
  }
});
</script>

<style scoped>
.point-detail-container {
  padding: 16px;
  max-height: 600px;
  overflow-y: auto;
}

.point-info-card {
  margin-bottom: 16px;
}

.point-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.point-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-right: 12px;
}

.point-basic-info {
  margin-bottom: 24px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.full-width {
  width: 100%;
}

.info-label {
  color: #606266;
  font-size: 14px;
  width: 100px;
  text-align: right;
}

.info-value {
  color: #303133;
  font-size: 14px;
  margin-left: 8px;
  flex: 1;
  max-width: calc(100% - 108px);
}

.ml-4 {
  margin-left: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #0f3aa0;
}

.point-map-section,
.recent-checkins {
  margin-bottom: 24px;
}

.map-container {
  border: 1px solid #0b3db1;
  border-radius: 4px;
  overflow: hidden;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.map-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-placeholder,
.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  background-color: #1a5bb1;
  color: #355cb1;
}

.image-error el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.no-map-data,
.no-checkins {
  padding: 40px 0;
  text-align: center;
  color: #909399;
  background-color: #124998;
  border-radius: 4px;
}

.point-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .info-row {
    flex-direction: column;
    align-items: flex-start;
  }

  .info-label {
    text-align: left;
    margin-bottom: 4px;
  }

  .info-value {
    max-width: 100%;
    margin-left: 0;
  }

  .ml-4 {
    margin-left: 0;
    margin-top: 12px;
  }
}
</style>